import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Card, Modal, message, Button, Form, Input, Row, Col, Radio } from 'antd';
import { FormInstance } from 'antd/lib/form';
import PropTypes from 'prop-types';
import PateoSearchForm from '@/components/common/PateoSearchForm';
import PateoAuthButtons from '@/components/common/PateoAuthButtons';
import PateoTable from '@/components/common/PateoTable';
import styles from '@/components/common/PateoTable/TableList.less';
import ApplyModal from './applyModal';

const statusData = {
  0: '',
  1: '已通过',
  2: '待提交',
  3: '已驳回'
}
const FormItem = Form.Item;
const TextArea = Input.TextArea;
const mapStateToProps = (state: any) => ({
  knowledgeApproval: state.knowledgeApproval,
  loading: state.loading.models['knowledgeApproval'],
});

class Approval extends PureComponent<any, any> {
  formRef = React.createRef<FormInstance>();
  rejectRef = React.createRef<FormInstance>();
  constructor(props: any) {
    super(props);
    this.state = {
      selectOptions: [],
      type: '1',
      formValues: {},
      extraArgs: {
        majorCodeList: [],
        status: ['1','2','3'],
        sort: [{
          orderBy: "createTime", 
          direction: "desc"
        }]
      },  //  必传参数
      userAccount: '',  //  用户名
      userId: '', //  用户id,
      currentId: '',  //  故障申请id
      formData: '', //  get查询参数
      rejectVisible: false, //  驳回弹框
      record: {},
      specialtyData: {},  //  当前弹框专业信息
      visible: false, //  故障弹框
    }
  }

  componentDidMount() {
    const { dispatch } = this.props;
    let userAccount: any = '';
    try {
      userAccount = sessionStorage.getItem('accountName');
    } catch (e) {}
    //  获取用户id
    dispatch({
      type: 'http/getDataWithRes',
      payload: { 
        url: '/findSidByAccountName',
        accountName: userAccount,
      },
      callback: (res: any) => {
        if (res.statusCode) {
          this.setState({
            userAccount: userAccount,
            userId: res.data || ''
          })
        }
      }
    })

    //  获取当前用户专业权限
    dispatch({
      type: 'http/getDataWithRes',
      payload: { 
        url: '/mscontent/knowledge/getPermissions',
        accountName: userAccount,
        current: 1,
        pageSize: 10,
      },
      callback: (res: any) => {
        if (res.statusCode === '0') {
          const { extraArgs: {majorCodeList, ...i}} = this.state; 
          //  专业下拉框
          const tempList = this.formatSpecialtyOption(res?.data?.list);
          //  账号专业
          const tempMajorCodeList = res?.data?.list && res?.data?.list.length > 0 ? res?.data?.list[0].majorCodes : [];
          const tempExtraArgs = {
            majorCodeList: tempMajorCodeList,
            ...i
          }
          this.setState({
            selectOptions: tempList,
            extraArgs: tempExtraArgs, //  设置必传参数
          })
          dispatch({
            type: 'knowledgeApproval/postFetchPage',
            payload: {
              url: '/mscontent/knowledge/apply/list',
              ...tempExtraArgs
            }
          });
        }
      }
    })
  }

  //  整理专业下拉选项
  formatSpecialtyOption = (list: any[]) => {
    let tempList: any[] = [];
    if (list && list.length > 0) {
      const data = list[0];
      data.majorIds && data.majorIds.forEach((v: any, idx: number) => {
        tempList.push({
          value: data.majorCodes[idx] + '',
          label: data.majorNames[idx],
          id: v,
        })
      })
    }
    return tempList
  }

  //  条件搜索
  onChange = (val: any) => {
    const data = {
      1: [1,2,3],
      2: [2],
      3: [1],
      4: [3],
    };
    const { dispatch } = this.props;
    const {formValues, extraArgs: {status, ...i}} = this.state
    this.setState({
      type: val,
      extraArgs: {
        status: data[val],
        ...i
      }
    }, () => {
      const { extraArgs } = this.state;
      dispatch({
        type: 'knowledgeApproval/postFetchPage',
        payload: {
          url: '/mscontent/knowledge/apply/list',
          ...extraArgs,
          ...formValues
        }
      });
    })
  }

  //  刷新页面
  refreshPage = () => {
    const { dispatch } = this.props;
    const { formValues, extraArgs: { status, ...i } } = this.state;
    const tempExtraArgs = {
      status: ['1','2','3'],
      ...i
    }
    this.setState({
      extraArgs: tempExtraArgs
    })
    dispatch({
      type: 'knowledgeApproval/postFetchPage',
      payload: {
        url: '/mscontent/knowledge/apply/list',
        ...formValues,
        ...tempExtraArgs,
      }
    });
  }

  //  查看故障
  handleViewBreakdown = (record: any) => {
    const { selectOptions } = this.state;
    const { majorCode } = record;
    let tempSpecialty = {}
    selectOptions.some((item: any) => {
      const status = item.value == majorCode;
      if (status) {
        tempSpecialty = {
          ...item
        }
      }
      return status;
    });
    this.setState({
      record,
      specialtyData: tempSpecialty,
      visible: true,
    })
  }

  //  关闭故障申请弹框
  closeApplyModal = () => {
    this.setState({
      specialtyData: {},
      visible: false,
    })
  }

  //  通过  √
  handleAccept = (record: any) => {
    const { dispatch } = this.props;
    const { userAccount, userId } = this.state;
    dispatch({
      type: 'http/putObj',
      payload: {
        url: '/mscontent/knowledge/apply/edit',
        id: record.id,
        userId,
        userAccount,
        status: 1,
      },
      callback: (res: any) => {
        if (res.statusCode == '0') {
          message.success('操作成功');
          this.refreshPage();
          this.cancel();
        }
      }
    })
  }

  //  驳回  √
  handleReject = (record: any) => {
    this.setState({
      rejectVisible: true,
      currentId: record.id,
    })
  }

  //  关闭驳回弹框
  cancel = () => {
    this.setState({
      rejectVisible: false
    })
  }

  //  确定操作
  save = () => {
    this.rejectRef.current?.submit();
  }

  //  提交驳回  √
  ok = (values: any) => {
    const { dispatch } = this.props;
    const { userAccount, userId, currentId } = this.state;
    const { rejectReason } = values;
    if (!(rejectReason && rejectReason.trim())) {
      message.warning('请输入驳回原因');
      return false;
    }
    if (!userId) {
      message.warning('获取用户信息失败，请刷新页面再试');
      return false;
    }
    dispatch({
      type: 'http/putObj',
      payload: {
        url: '/mscontent/knowledge/apply/edit',
        id: currentId,
        userId,
        userAccount,
        status: 3,
        rejectReason
      },
      callback: (res: any) => {
        if (res.statusCode == '0') {
          message.success('操作成功');
          this.cancel();
          this.refreshPage();
        }
      }
    })
  }

  render() {
    const {
      knowledgeApproval: {
        pageData: { 
          list,
          pagination, 
          allCount, 
          approveRejectCount, 
          approveSuccessCount, 
          approvingCount, 
          noCommitCount,
        }
      },
      loading,
      location: { pathname = '/' },
    } = this.props;
    const tempAllCount = approveRejectCount + approveSuccessCount + approvingCount;
    const { formValues, type, selectOptions, rejectVisible, visible, specialtyData, record, extraArgs } = this.state;
    const page = {
      current: pagination.current,
      pageSize: pagination.pageSize,
      total: pagination.total,
    }
    const columns = [
      {
        title: '序号',
        dataIndex: 'no',
        width: 60,
        render: (text: any, record: any, index: any) => {
          return index + 1 + (page.current - 1) * page.pageSize;
        },
      },
      {
        title: '专业编码',
        dataIndex: 'majorCode',
      },
      {
        title: '故障分类',
        dataIndex: 'faultType',
        render: (text: any, record: any) => {
          return <Button type="link" style={{ padding: 0 }} onClick={() => this.handleViewBreakdown(record)}>{text}</Button>;
        }
      },
      {
        title: '提交人',
        dataIndex: 'createBy',
      },
      {
        title: '审批人',
        dataIndex: 'approveBy',
      },
      {
        title: '审批时间',
        dataIndex: 'approveTime',
      },
      {
        title: '审批状态',
        dataIndex: '审批状态',
        width: 160,
        render: (text: any, record: any) => {
          let btns: any = [];
          if (record.status == 2) {
            btns = [
              {
                title: '通过',
                key: 'accept',
                auth: 'knowledgeApproval_accept',
                onConfirm: () => this.handleAccept(record),
              },
              {
                title: '驳回',
                key: 'reject',
                auth: 'knowledgeApproval_reject',
                onConfirm: () => this.handleReject(record),
              },
            ]
          }
          return btns.length > 0 ? <PateoAuthButtons btns={btns} max={2} pathname={pathname} /> : statusData[record.status];
        }
      }
    ]

    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...page,
      showTotal: () => (
        <span>共&nbsp;{page === undefined ? 0 : page.total}&nbsp;条</span>
      ),
    };

    const tableProps = {
      columns,
      dataSource: list,
      loading,
      rowKey: (record: any) => record.id,
      pagination: paginationProps,
      scroll: { x: 'max-content' },
    };

    const searchItems = [
      {
        title: '专业',
        type: 'select',
        key: 'majorCode',
        selectOptions: selectOptions || [],
      },
      {
        type: 'input',
        title: '故障分类',
        key: 'faultType',
      },
    ]

    const footer = (
      <div>
        <Button size="small" onClick={this.cancel}>
          取消
        </Button>
        {/* loading={loading} */}
        <Button size="small" onClick={this.save} type="primary">
          确定
        </Button>
      </div>
    );

    return (
      <div>
        <Card bordered={false}>
          <PateoSearchForm
            searchItems={searchItems}
            fetchParams={{ type: 'knowledgeApproval/postFetchPage', url: '/mscontent/knowledge/apply/list' }}
            saveFormValues={(val: any) =>
              this.setState({ formValues: Object.assign(formValues, val) })
            }
            extraArgs={extraArgs}
            handleFormReset={() => {
              const { extraArgs: {status, ...i}} = this.state;
              this.setState({ 
                formValues: {},
                extraArgs: {
                  status: ['1','2','3'],
                  ...i,
                },
                type: '1',
              })
            }}
          />
        </Card>
        <Card className={styles.standardTable}>
          <div style={{ textAlign: 'right', marginBottom: '12px' }}> 
            <Radio.Group 
              onChange={({target: { value }}) => {
                this.onChange(value)
              }}
              value={type}
              optionType="button"
              buttonStyle="solid"
            >
              <Radio.Button value="1">全部({tempAllCount})</Radio.Button>
              <Radio.Button value="2">待审批({approvingCount})</Radio.Button>
              <Radio.Button value="3">审批通过({approveSuccessCount})</Radio.Button>
              <Radio.Button value="4">审批驳回({approveRejectCount})</Radio.Button>
            </Radio.Group>
          </div>
          <PateoTable
            extraHandle={true}
            tableProps={tableProps}
            fetchParams={{ type: 'knowledgeApproval/postFetchPage', url: '/mscontent/knowledge/apply/list', extraArgs: { ...extraArgs } }}
            formValues={formValues}
          />
        </Card>
        <Modal
          style={{ top: 20 }}
          footer={footer}
          title="驳回原因"
          width={500}
          visible={rejectVisible}
          onCancel={this.cancel}
        >
          <Form
            style={{ marginTop: 12 }}
            ref={this.rejectRef}
            onFinish={this.ok}
          >
            <FormItem
              // {...formItemLayout}
              colon={false}
              style={{ marginBottom: 0 }}
              label=" "
              name="rejectReason"
              rules={[]}
            >
              <TextArea rows={4} placeholder="填写原因" />
            </FormItem>
          </Form>
        </Modal>
        <ApplyModal
          onRef={(modalRef: any) => (this.applyModal = modalRef)}
          modalVisible={visible}
          record={record}
          specialtyData={specialtyData}
          closeModal={this.closeApplyModal}
        />
      </div>
    )
  }
}
export default connect(mapStateToProps)(Approval);
